#include <sys/types.h>       
#include <sys/socket.h>
#include<iostream>
#include<netinet/in.h>
#include <strings.h>
#include <string.h>
#include"error.hpp"
#include <arpa/inet.h>
#include<functional>
#include<unordered_map>
#include"CircularQueue.hpp"
#include"lockguard.hpp"
#include"pthread.hpp"
#include<functional>
namespace udp_serve
{

    const static uint16_t default_port = 8080;
    using func_t = std::function<std::string(std::string)>;//对一个包装器重命名了,可以接收string(string)这样的函数名
    class UdpServer
    {
    public:
        // UdpServer(const std::string ip,u_int16_t port = default_port)//缺省参数要从左往右给
        UdpServer(u_int16_t port = default_port)//缺省参数要从左往右给
        :_port(port)
        {
            p_ = new Thread(1,std::bind(&UdpServer::Recv,this));
            // p_ = new Thread(1,std::bind(&UdpServer::Recv(),this));错误写法
            C_ = new Thread(1,std::bind(&UdpServer::broadcast,this));
        }
        ~UdpServer()
        {
            pthread_mutex_destroy(&mutex_);
            //不等待回收,主线程就会直接退出
            p_->join();
            C_->join();
        }
        void start()
        {            
            //打开网络文件
            socket_ = socket(AF_INET,SOCK_DGRAM,0);
            if(socket_ < 0)
            {
                std::cout<<"create socket error"<<strerror(errno)<<std::endl;
                exit(SOCKET_ERR);
            }
            std::cout<<"create socket successs"<<std::endl;
            
            //绑定端口号和ip地址
            struct sockaddr_in sock;//头文件<netinet/in.h>
            bzero(&sock,sizeof(sock));
            sock.sin_addr.s_addr = INADDR_ANY;//设置ip地址 表示所有的ip的地址
            sock.sin_port = htons(_port);
            sock.sin_family = AF_INET; 
            if(bind(socket_,(sockaddr*)(&sock),sizeof(sock)) < 0)
            {
                std::cout<<"bind error "<<strerror(errno)<<std::endl;
                exit(BIND_ERR);
            }
            std::cout<<"bind successs"<<std::endl;
            p_->Run();
            C_->Run();
        }
        void adduser(std::string name, struct sockaddr_in sock)
        {
            if(!online_.count(name))//返回1:存在,返回0:不存在
                online_[name] = sock;
        }
        //开始接受数据
        void Recv()
        {
           while(true)
           {
                struct sockaddr_in sock;
                char buffer[1024] = {0};
                socklen_t len = sizeof(sock);
                int n = recvfrom(socket_,buffer,sizeof(buffer)-1,0,(sockaddr*)&sock,&len);//len的意义?
                buffer[n] = '\0';
                std::string clientip = inet_ntoa(sock.sin_addr);
                u_int16_t clientport = ntohs(sock.sin_port);
                std::string name;
                name += clientip;
                name += "-";
                name += to_string(clientport);
                name += "#";
                adduser(name,sock);
                name += buffer;
                rp_.push(name);
                std::cout<<clientip<<"-"<<clientport<<"# "<<buffer<<std::endl;//输出处理前的字符
                //上面是在接收客户端的ip和端口号
                // sendto(socket_, rets.c_str(),rets.size(),0,(sockaddr*)&sock,len);//不用转网络序列,是因为我们接收的时候就没转成主机序列
           }
        }
        void broadcast()//负责给所有的客户端发消息
        {
            while(true)
            {
                std::string msg;
                rp_.pop(msg);//获取一条消息
                std::vector<sockaddr_in> tmp;
                {
                    LockGuard lock(&mutex_);
                    for(auto e : online_)
                    {
                        tmp.push_back(e.second);
                    }
                }
                for(auto e : tmp)
                {
                    sendto(socket_, msg.c_str(),msg.size(),0,(sockaddr*)&e,sizeof(e));//不用转网络序列,是因为我们接收的时候就没转成主机序列
                }
            }
           
        }
    private:
        // func_t func_;
        int socket_;
        // std::string _ip;
        pthread_mutex_t mutex_;
        std::unordered_map<std::string,sockaddr_in> online_;//保存用户名,ip和端口号
        CirQueue<std::string> rp_;
        Thread* p_;
        Thread* C_;
        uint16_t _port;
    };
};
